package cn.hfatec.shms.web.xc.xcGsgj.service;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.advice.annotation.MysqlDataSource;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.utils.ExcelUtil;
import cn.hfatec.shms.web.cw.cwChtb.model.CwChtb;
import cn.hfatec.shms.web.cw.cwChtb.model.CwChtbParams;
import cn.hfatec.shms.web.vip.vipXxb.model.VipCheck;
import cn.hfatec.shms.web.vip.vipXxb.model.VipXxb;
import cn.hfatec.shms.web.xc.xcGsgj.dao.XcGsgjDao;
import cn.hfatec.shms.web.xc.xcGsgj.model.GsgjCheck;
import cn.hfatec.shms.web.xc.xcGsgj.model.XcGsgj;
import cn.hfatec.shms.web.xc.xcGsgj.model.XcGsgjParams;
import cn.hfatec.shms.web.yk.ykXmmx.model.YkXmmx;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("XcGsgjService")
public class XcGsgjService {

    public static final String BEAN_ID = "XcGsgjService";

    //注入Dao层
    @Resource(name = "XcGsgjDao")
    private XcGsgjDao xcGsgjDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;
    @Resource(name = "shmsProperties")
    private ShmsProperties shmsProperties;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param xcGsgjParams
     * @param page
     */
    @Transactional
    public Table queryXcGsgjTable(XcGsgjParams xcGsgjParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", xcGsgjParams);
        return baseDao.queryTableByPage("queryXcGsgj", params, page);
    }

    /**
     * 根据ID获取数据
     *
     * @param xcGsgjParams
     */
    @Transactional
    public XcGsgj xcGsgjHj(XcGsgjParams xcGsgjParams) {

        return xcGsgjDao.queryXcGsgjHj(xcGsgjParams);
    }

    /**
     * 插入数据
     *
     * @param xcGsgj
     */
    @Transactional
    public void saveXcGsgj(XcGsgj xcGsgj) {
        if (xcGsgj.getId() != null) {
            XcGsgj result = getXcGsgj(xcGsgj.getId());
            if (result != null) {
                xcGsgjDao.update(xcGsgj);
            } else {
                xcGsgjDao.insert(xcGsgj);
            }
        } else {
            xcGsgjDao.insert(xcGsgj);
        }
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    public void deleteXcGsgj(Integer id) {

        xcGsgjDao.delete(id);
    }

    /**
     * 删除数据
     *
     * @param xcGsgjList
     */
    @Transactional
    public void deleteXcGsgjBatch(List<String> xcGsgjList) {
        for (String id : xcGsgjList) {
            deleteXcGsgj(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    public XcGsgj getXcGsgj(Integer id) {

        return xcGsgjDao.getXcGsgjById(id);
    }

    /**
     * 根据ID获取数据
     *
     * @param ZDate
     */
    @Transactional
    public List<XcGsgj> getYkXcGsgjGx(String ZDate,String gxEnd) {

        return xcGsgjDao.getYkXcGsgjGx(ZDate,gxEnd);
    }

    /**
     * 删除数据
     *
     * @param ZDate
     */
    @Transactional
    @MysqlDataSource
    public void deleteYkXmmxhs(String ZDate,String gxEnd) {

        xcGsgjDao.deleteHs(ZDate,gxEnd);
    }

    /**
     * 修改跟进人员数据
     *
     * @param xcGsgjList
     */
    @Transactional
    @MysqlDataSource
    public void updateXcGsgjBatch(List<String> xcGsgjList, String userName) throws InvocationTargetException, IllegalAccessException {
        for (String id : xcGsgjList) {
            XcGsgj xcGsgj = new XcGsgj();
            xcGsgj.setId(Integer.valueOf(id));
            xcGsgj.setUserName(userName);
            xcGsgjDao.update(xcGsgj);
        }
    }

    /**
     * @param path
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @Transactional
    @MysqlDataSource
    public String importCust(String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filePath = path.substring(path.indexOf("/upload") + 7);
        User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
        if (user == null) {
            throw new NotAuthException("用户未授权");
        }
        String uploadPath = shmsProperties.getUploadPath();
        File file = new File(uploadPath + File.separator + filePath);
        boolean flag = false;
        String rule = "^1[358]\\d{9}$";
        String errorMsg = "";
        Workbook workbook = null;
        workbook = WorkbookFactory.create(file);
        Sheet sh = workbook.getSheetAt(0);//
        List<GsgjCheck> potentialCusts = this.buildCustWithAjaxUpload(sh);//
        if (potentialCusts != null && potentialCusts.size() > 0) {
            for (GsgjCheck gsgjCheck : potentialCusts) {
                //判读是否为有效数据

                if (gsgjCheck.isValid()) {
                    XcGsgj xcGsgj = gsgjCheck.getXcGsgjcGsgj();
                    saveXcGsgj(xcGsgj);
                    flag = true;
                } else {//无效数据
                    errorMsg += "第" + gsgjCheck.getRowNumber() + "行的姓名或录入日期为空，不能导入!";
                }
            }
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "导入的文件无符合数据").toString();
        }

        if (flag) {
            if ("".equals(errorMsg)) {
                return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入成功!" + errorMsg).toString();
            }
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "部分导入成功!" + errorMsg).toString();
        } else {
            return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "导入失败!" + errorMsg).toString();
        }

    }

    /**
     * 读取潜在客户导入的数据
     *
     * @param sh
     * @return
     * @throws Exception
     */
    @Transactional
    @MysqlDataSource
    private List<GsgjCheck> buildCustWithAjaxUpload(Sheet sh) throws Exception {
        List<GsgjCheck> checks = new ArrayList<GsgjCheck>();
        int rows = sh.getLastRowNum() + 1 - sh.getFirstRowNum(); // 总行数
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);
        ExcelUtil excelUtil = new ExcelUtil();
        for (int i = 1; i < rows; i++) {
            boolean flag = true;//数据是否有效(客户姓名，手机号存在)
            boolean flag2 = false;//判断是否该行有数据
            XcGsgj xcGsgj = new XcGsgj();
            GsgjCheck gsgjCheck = new GsgjCheck();
            gsgjCheck.setRowNumber(i + 1);
            gsgjCheck.setValid(true);
            String str = "";//下拉框
            // HSSFRow row = sh.getRow(i);//excel97-2003写法
            Row row = sh.getRow(i);
//            int cols = row.getLastCellNum() + 1 - row.getFirstCellNum(); // 该行的总列数
            Iterator cells = row.cellIterator();
            int j = 0;
            while (cells.hasNext()) {
                //判断行数据的客户姓名和电话是否为空，某一项为空则不执行循环
                if (StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, 0))) {
                    for (int r = 0; r <= 10; r++) {
                        if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, r))) {
                            if (!flag2) {
                                gsgjCheck.setValid(false);
                                flag2 = true;
                            }
                        }
                    }
                    flag = false;
                    break;
                }

//                HSSFCell cell = (HSSFCell) cells.next();//excel97-2003写法
                XSSFCell cell = (XSSFCell) cells.next();

                if (j == 0) {
                    //卡号
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setSpareB(ExcelUtil.getStringRowCellValue(row, j));
                    }

                }
                if (j == 1) {
                    //卡号
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setRecordNo(ExcelUtil.getStringRowCellValue(row, j));
                    }

                } else if (j == 2) {
                    //

                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setTjStart(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 3) {
                    // 年龄
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setCardNo(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 4) {
                    // 年龄
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setCustomerName(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 5) {
                    // 年龄
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setSex(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 6) {
                    // 年龄
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setAge(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 7) {
                    // 年龄
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setPhone(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 8) {

                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setIdNo(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 9) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setWeight(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 10) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setDisease(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 11) {

                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setZDate(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 12) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setStatus(ExcelUtil.getStringRowCellValue(row, j));
                    }
                } else if (j == 13) {
                    if (!StringUtils.isEmpty(excelUtil.getStringRowCellValue(row, j))) {
                        xcGsgj.setSpareA(ExcelUtil.getStringRowCellValue(row, j));
                    }
                }
                j++;
            }
            if (flag) {
//                 list.add(cust);
                gsgjCheck.setXcGsgjcGsgj(xcGsgj);
                checks.add(gsgjCheck);
            } else {
//                vipCheck.setCustom(cust);
                if (flag2) {
                    checks.add(gsgjCheck);
                }
            }
        }
        return checks;
    }

    public String stringDate(Date billTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sDate = sdf.format(billTime);
        return sDate;
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(XcGsgjParams xcGsgjParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = xcGsgjDao.queryXcGsgj(xcGsgjParams);
            List nameList = new ArrayList();
            nameList.add("体检ID");
            nameList.add("体检日期");
            nameList.add("卡号");
            nameList.add("客户姓名");
            nameList.add("性别");
            nameList.add("年龄");
            nameList.add("联系电话");
            nameList.add("体重");
            nameList.add("疾病诊断");
            nameList.add("总检日期");
            nameList.add("跟进人");
            nameList.add("是否回访");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> yesnoList = CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("高筛跟进");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        XcGsgj xcGsgj = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            xcGsgj = (XcGsgj) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (xcGsgj.getSpareB() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(xcGsgj.getSpareB());
            }
            if (xcGsgj.getTjStart() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(xcGsgj.getTjStart());
            }
            if (xcGsgj.getCardNo() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(xcGsgj.getCardNo());
            }
            if (xcGsgj.getCustomerName() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(xcGsgj.getCustomerName());
            }
            if (xcGsgj.getSex() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                row.createCell((short) 4).setCellValue(xcGsgj.getSex());
            }
            if (xcGsgj.getAge() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(xcGsgj.getAge());
            }
            if (xcGsgj.getPhone() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {
                row.createCell((short) 6).setCellValue(xcGsgj.getPhone());
            }
            if (xcGsgj.getWeight() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                row.createCell((short) 7).setCellValue(xcGsgj.getWeight());
            }
            if (xcGsgj.getDisease() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(xcGsgj.getDisease());
            }
            if (xcGsgj.getZDate() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                row.createCell((short) 9).setCellValue(xcGsgj.getZDate());
            }
            if (xcGsgj.getUserName() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(xcGsgj.getUserName());
            }
            if (xcGsgj.getSpareD() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                for (CodeInfo c : yesnoList) {//汉化性别信息
                    if (c.getValue().equals(xcGsgj.getSpareD() + "")) {
                        row.createCell((short) 11).setCellValue(c.getContent());
                        break;
                    }
                }
            }
        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }
        return wb;
    }

    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }
}